<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>文本比较工具</title>
    <link rel="stylesheet" href="../../bootstrap/bootstrap.min.css">
    <style>
        .diff span {
            background-color: #fff;
        }

        .diff del {
            background-color: #ffe6e6;
            text-decoration: line-through;
        }

        .diff ins {
            background-color: #e6ffe6;
            text-decoration: underline;
        }
    </style>
</head>

<body>

    <div class="container mt-5">
        <h1 class="mb-4">文本比较工具</h1>

        <form>
            <div class="mb-3">
                <label for="text1" class="form-label">文本1：</label>
                <textarea class="form-control" id="text1" rows="5"></textarea>
            </div>

            <div class="mb-3">
                <label for="text2" class="form-label">文本2：</label>
                <textarea class="form-control" id="text2" rows="5"></textarea>
            </div>

            <button type="button" class="btn btn-primary" onclick="compare()">比较</button>
        </form>

        <hr>

        <div class="row">
            <div class="col-sm-6">
                <h3>文本1</h3>
                <div id="text1-diff"></div>
            </div>
            <div class="col-sm-6">
                <h3>文本2</h3>
                <div id="text2-diff"></div>
            </div>
        </div>

    </div>

    <script src="../../js/diff_match_patch.js"></script>
    <script>
        function compare() {
            // 获取文本框中的文本内容
            const text1 = document.getElementById("text1").value;
            const text2 = document.getElementById("text2").value;

            // 计算差异
            const dmp = new diff_match_patch();
            const diffs = dmp.diff_main(text1, text2);
            dmp.diff_cleanupSemantic(diffs);

            // 显示差异
            let html1 = '';
            let html2 = '';
            for (let i = 0; i < diffs.length; i++) {
                const diff = diffs[i];
                const type = diff[0];
                const value = diff[1];

                if (type === 0) {
                    html1 += '<span>' + value + '</span>';
                    html2 += '<span>' + value + '</span>';
                } else if (type === -1) {
                    html1 += '<del>' + value + '</del>';
                    html2 += '<ins>' + value + '</ins>';
                } else if (type === 1) {
                    html1 += '<ins>' + value + '</ins>';
                    html2 += '<del>' + value + '</del>';
                }
            }

            document.getElementById('text1-diff').innerHTML = html1;
            document.getElementById('text2-diff').innerHTML = html2;
        }

    </script>


</body>

</html>
